var FlyCesium = {
    cesiumViewer: null,
    draw3DObj: null,
    drawHelper: null,
    isDrawFly: false, //设定路线模式
    drawPolyline: null, //飞行绘制路线
    data: [],
    ajax: "",
    Init: function (cesiumViewer, drawHelper) {
        this.ajax = getBaseplatformPort() + "map/";
        this.cesiumViewer = cesiumViewer; //cesium对象
        this.drawHelper = drawHelper; //drawHelper对象
        this.InitEvent();
        this.loadData();
    },
    InitEvent: function () {
        //飞行路径顶端部分的切换事件
        $(".fly3DPaths_tab li").bind("click", function () {
            $('.fly3DPaths_tab_ul>li').each(function (index) {
                $('.fly3DPaths_tab_ul>li').eq(index).removeClass('select');
            })
            //三角形标识切换
            switch ($(this).index()) {
                case 0: //预设路线
                    $('#overFlyClick').addClass('select');
                    $("#overFlyPage").css({ display: "block" });
                    $("#drawFlyPage").css({ display: "none" });
                    FlyCesium.loadData();
                    break;
                case 1: //手动绘制
                    $('#drawFlyCilck').addClass('select');
                    $("#overFlyPage").css({ display: "none" });
                    $("#drawFlyPage").css({ display: "block" });
                    break;
            }
        });
        //开始飞行
        $("#start_Fly3DPaths").click(function () {
            if (FlyCesium.draw3DObj) {
                FlyCesium.showFly3DPaths(FlyCesium.draw3DObj);
            } else {
                showMsgLayer("漫游路线不存在");
            }
        });
        //暂停飞行
        $("#pause_Fly3DPaths").click(function () {
            FlyCesium.pauseFly3DPaths();
        });
        $("#pause_Fly3DPaths2").click(function () {
            FlyCesium.pauseFly3DPaths();
        });
        //向前飞行
        $("#playForward_Fly3DPaths").click(function () {
            FlyCesium.playForwardFly3DPaths();
        });
        //向后飞行
        $("#playReverse_Fly3DPaths").click(function () {
            FlyCesium.playReverseFly3DPaths();
        });
        //退出飞行
        $("#stop_Fly3DPaths").click(function () {
            $("#cesiumFly3DPaths").click();
            FlyCesium.stopFly3DPaths();
        });
        //清空路线
        $("#clear_Fly3DPaths").click(function () {
            FlyCesium.clearFly3DPaths();
        });

        //设定路线
        $("#draw_Fly3DPaths").click(function () {
            if (!FlyCesium.drawHelper) {
                FlyCesium.drawHelper = new DrawHelper(FlyCesium.cesiumViewer);
            }
            FlyCesium.draw3DObj = FlyCesium.DrawFly3DPaths(FlyCesium.drawHelper);
        });
        //保存路线
        $("#save_Fly3DPaths").click(function () {
            if (FlyCesium.draw3DObj && FlyCesium.isDrawFly) {
                layer.open({
                    type: 1,
                    area: ['300px', '200px'],
                    title: '保存路线',
                    content: '<div style="text-align: center;"><span>名称:</span><input style="width: 230px;display: inline;margin-left:12px;margin-top: 10px;" class="layui-input" type="text" id="FlyAdd_name" value="' + name + '"></div>',
                    shade: 0,
                    btn: ['确定', '返回'],
                    btn1: function (index, layero) {
                        var name = $("#FlyAdd_name").val().replace(" ", "");
                        if (name) {
                            for (var i = 0 ; i < FlyCesium.data.length ; i++) {
                                if (FlyCesium.data[i].NAME === name) {
                                    showMsgLayer("此名称已存在！");
                                    return;
                                }
                            }
                            var draw3DObj = JSON.stringify(FlyCesium.draw3DObj); //将JSON对象转化为JSON字符
                            var TbFly = { id: Math.random().toString(36).substr(2), name: name, geojson: draw3DObj };
                            $.ajaxSettings.async = false;
                            $.ajax({
                                type: "post",
                                async: false,
                                crossDomain : true,
                                xhrFields : {
                                    withCredentials: true
                                },
                                url: FlyCesium.ajax + "addCollection",
                                data: {
                                    name: name,
                                    info: JSON.stringify(TbFly),
                                    type: "fly"
                                },
                                datatype: "json",
                                success: function (result) {
                                    result = JSON.parse(result);
                                    if (result.code == 200) {
                                        showMsgLayer("保存成功！");
                                        FlyCesium.data.push(TbFly);
                                        $("#overFlyClick").click();
                                        FlyCesium.clearFly3DPaths();
                                        layer.closeAll();
                                    }
                                }
                            });
                        } else {
                            showMsgLayer("请先输入名称！");
                        }
                    },
                    btn2: function (index, layero) {
                        layer.closeAll();
                    },
                    cancel: function (layero, index) {
                        layer.closeAll();
                    }
                });
            } else {
                showMsgLayer("设定的漫游路线不存在，请绘制再保存");
            }
        });
    },
    //飞行路径列表表格监听事件
    flyTableOnclick: function () {
        $(".flyHandle").click(function () {
            var trSeq = $(this).parent().parent().parent().find("tr").index($(this).parent().parent()); //选中的哪行
            var geojson = $("#overFly_table tr:gt(0):eq(" + trSeq + ") td:eq(5)").text(); //获取选中行的geojson列值
            geojson = eval("(" + geojson + ")");
            FlyCesium.draw3DObj = JSON.parse(geojson.geojson);
            FlyCesium.showFly3DPaths(FlyCesium.draw3DObj);
            $("#drawFlyCilck").click();
        });
        $(".flyDelete").click(function () {
            var trSeq = $(this).parent().parent().parent().find("tr").index($(this).parent().parent()); //选中的哪行
            var flyId = $("#overFly_table tr:gt(0):eq(" + trSeq + ") td:eq(4)").text(); //获取选中行的id列值
            $.ajaxSettings.async = false;
            $.ajax({
                type: "post",
                async: false,
                crossDomain : true,
                xhrFields : {
                    withCredentials: true
                },
                //url: m_MapConfigLayers.mapconfig.flyAjax,
                url: FlyCesium.ajax + "deleteCollection",
                data: {
                    type: "fly",
                    id: flyId
                },
                datatype: "json",
                success: function (result) {
                    result = JSON.parse(result);
                    if (result.code == 200) {
                        showMsgLayer("删除成功！");
                        FlyCesium.loadData();
                    } else {
                        showMsgLayer("删除失败！");
                    }
                }
            });
        });
    },
    /**
     * 从数组中移除指定的元素,要是存在的话
     @ serviceArray筛选数组
     @ id移除元素id
     */
    delElement: function (serviceArray, id) {
        var array = [];
        for (var i = 0; i < serviceArray.length; i++) {
            if (serviceArray[i].id != id) {
                array.push(serviceArray[i]);
            }
        }
        return array;
    },
    /**
     * 从数组中修改指定的元素,要是存在的话
     @ serviceArray筛选数组
     @ id修改元素id
     @ name修改元素名称
     */
    modifyElement: function (serviceArray, id, name) {
        var array = [];
        for (var i = 0; i < serviceArray.length; i++) {
            if (serviceArray[i].id == id) {
                serviceArray[i].name = name;
            }
            array.push(serviceArray[i]);
        }
        return array;
    },
    loadData: function () {
        $.ajaxSettings.async = false;
        $.ajax({
            type: "post",
            async: false,
            crossDomain : true,
            xhrFields : {
                withCredentials: true
            },
            url: FlyCesium.ajax + "getCollection",
            data: {
                type: "fly"
            },
            datatype: "json",
            success: function (result) {
                result = JSON.parse(result);
                if (result.code == 200) {
                    FlyCesium.data = result.data;
                } else {
                    showMsgLayer("获取飞行数据列表失败！");
                }
            }
        });

        var data = FlyCesium.data;
        var html = ''
        if (data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                var flydata = data[i];
                html += '<tr>' +
                    // '<td><input type="checkbox" name="FLYNAME" id="'+flydata.id+'" style="cursor: pointer;" onchange=""></td>'+
                    '<td style="">' + flydata.NAME + '</td>' +
                    '<td style=""><button class="btn btn-xs flyHandle" ><i class="layui-icon">&#xe652;</i></button>' +
                    '<button class="btn btn-xs flyDelete" style="margin-left: 15px;"><i class="layui-icon">&#x1007;</i></button></td>' +
                    //'<td style="width:20px;"><button class="btn btn-default btn-xs" style="color:#fff;">飞行</button></td>'+
                    '<td style="display:none;"><button class="btn btn-default btn-xs" style="color:#fff;display:none;">修改</button></td>' +
                    '<td style="display: none;"></td>' +
                    "<td style='display:none;'><a style='color:black;text-decoration:none;font-size:13px;'>" + flydata.ID + "</a></td>" +
                    "<td style='display:none;'><a style='color:black;text-decoration:none;font-size:13px;'>" + flydata.INFO + "</a></td>" +
                    "<td style='display:none;'><a style='color:black;text-decoration:none;font-size:13px;'>" + flydata.INFO.position + "</a></td>" +
                    "<td style='display:none;'><a style='color:black;text-decoration:none;font-size:13px;'>" + flydata.INFO.orientation + "</a></td>" +
                    '</tr>';
            }
            $("#overFly_table tbody").html(html);
            $('#overFly_table').find('td:eq(2)').hide(); //隐藏orientation字段列
            $('#overFly_table').find('td:eq(3)').hide(); //隐藏orientation字段列
            $('#overFly_table').find('td:eq(4)').hide(); //隐藏id字段列
            $('#overFly_table').find('td:eq(5)').hide(); //隐藏geojson字段列
            $('#overFly_table').find('td:eq(6)').hide(); //隐藏position字段列
            $('#overFly_table').find('th:eq(2)').hide(); //隐藏修改行
            $('#overFly_table').find('th:eq(3)').hide(); //隐藏删除行
            FlyCesium.flyTableOnclick();
        } else {
            $("#overFly_table tbody").html("");
        }
    },
    /**
     * 清空漫游路径
     * @method stopFly3DPaths
     * @param
     * @return
     */
    clearFly3DPaths: function () {
        this.cesiumViewer.trackedEntity = undefined;
        FlyCesium.isDrawFly = false;
        FlyCesium.draw3DObj = null;
        //removeAllEntities();
        this.cesiumViewer.entities.removeAll(); //清空所有模型
        // this.cesiumViewer.entities.remove(this.entityFly);
        //清空绘制飞行路线
        if (this.drawPolyline) {
            this.cesiumViewer.scene.primitives.remove(this.drawPolyline);
            this.drawPolyline = null;
        }
    },
    /**
     * 飞行漫游路径
     * @method showFly3DPaths
     * @param  pathsData 飞行路径信息,格式如下:{"orientation":{"heading":2.411783930363565,"pitch":-0.21097267398444197,"roll":0.0015622392231300353},"position": {"x":-2206260.239730831,"y":5510911.392077349,"z":2331987.10863007}, "geometry":{"type": "LineString", "coordinates": [[101.80089882736969, 26.60700234866561], [101.80082205161088, 26.607156056057718]]} }
     * @param  position 飞行路径跳转位置  同时也要设置飞行的高度
     * @return
     */
    showFly3DPaths: function (pathsData) {
        var T = this;
        this.clearFly3DPaths();
        T.cesiumViewer.camera.setView({
            destination: pathsData.position,
            orientation: pathsData.orientation,
        });
        setTimeout(function () {
            executeFly3D();
        }, 200);

        function executeFly3D() {
            var terrainHeight = 1600;
            if (pathsData && pathsData.geometry) {
                var positionA = pathsData.geometry.coordinates;
                var position = [];
                if (positionA.length > 0) {
                    for (var i = 0; i < positionA.length; i++) {
                        var x = positionA[i][0];
                        var y = positionA[i][1];
                        position.push({ x: x, y: y, z: terrainHeight });
                    }
                } else {
                    return;
                }

                function computeCirclularFlight() {
                    var property = new Cesium.SampledPositionProperty();
                    for (var i = 0; i < position.length; i++) {
                        if (i == 0) {
                            var time = Cesium.JulianDate.addSeconds(start, i, new Cesium.JulianDate());
                            //var _position = Cesium.Cartesian3.fromDegrees(position[i].x, position[i].y, 1170);
                            var _position = Cesium.Cartesian3.fromDegrees(position[i].x, position[i].y, terrainHeight);
                            property.addSample(time, _position);
                        }
                        if (i < 10000 && i > 0) {
                            var position_a = new Cesium.Cartesian3(property._property._values[i * 3 - 3], property._property._values[i * 3 - 2], property._property._values[i * 3 - 1]);
                            var _position = Cesium.Cartesian3.fromDegrees(position[i].x, position[i].y, terrainHeight);
                            var positions = [Cesium.Ellipsoid.WGS84.cartesianToCartographic(position_a), Cesium.Ellipsoid.WGS84.cartesianToCartographic(_position)];
                            var a = new Cesium.EllipsoidGeodesic(positions[0], positions[1]);
                            var long = a.surfaceDistance;
                            var _time = long / 50;
                            var time = Cesium.JulianDate.addSeconds(property._property._times[i - 1], _time, new Cesium.JulianDate());
                            property.addSample(time, _position);
                        }
                    }
                    return property;
                }
                var start = Cesium.JulianDate.fromDate(new Date(2018, 3, 15, 16));
                var stop = Cesium.JulianDate.addSeconds(start, 30000, new Cesium.JulianDate());

                //Make sure viewer is at the desired time.
                T.cesiumViewer.clock.startTime = start.clone();
                T.cesiumViewer.clock.stopTime = stop.clone();
                T.cesiumViewer.clock.currentTime = start.clone();
                T.cesiumViewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
                //T.cesiumViewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED; //
                //T.cesiumViewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK; //
                //T.cesiumViewer.clock.multiplier = 1000000; //值越大，飞行越快
                //T.cesiumViewer.clock.multiplier = 0.6;
                T.cesiumViewer.clock.canAnimate = false;
                T.cesiumViewer.clock.shouldAnimate = true; //设置时间轴动态效果

                var _position = computeCirclularFlight();

                T.entityFly = T.cesiumViewer.entities.add({
                    //Set the entity availability to the same interval as the simulation time.
                    availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
                        start: start,
                        stop: stop
                    })]),
                    position: _position,
                    orientation: new Cesium.VelocityOrientationProperty(_position),
                    // polyline : {
                    //     positions : _position,
                    //     width :10,
                    //     heightReference : Cesium.HeightReference.CLAMP_TO_GROUND,
                    //     clampToGround : true,
                    //     material : new Cesium.PolylineGlowMaterialProperty({
                    //         glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
                    //         color: Cesium.Color.YELLOW.withAlpha(1)
                    //     })
                    // },
                    point: {
                        color: Cesium.Color.fromAlpha(Cesium.Color.WHITE, 0.01),
                        outlineColor: Cesium.Color.fromAlpha(Cesium.Color.WHITE, 0.01),
                        outlineWidth: 1,
                        pixelSize: 15,
                    },
                    path: {
                        resolution: 1,
                        material: new Cesium.PolylineGlowMaterialProperty({
                            glowPower: 0.1,
                            color: Cesium.Color.fromAlpha(Cesium.Color.YELLOW, 0.000001)
                        }),
                        width: 10
                    }
                });
                T.cesiumViewer.trackedEntity = T.entityFly;
                // setTimeout(function() {
                //     T.cesiumViewer.camera.zoomOut(500.0); //缩小地图，避免底图没有数据
                // }, 100);
            } else {
                return;
            }
        }
    },
    /**
     * 暂停飞行漫游路径
     * @method pauseFly3DPaths
     * @return
     */
    pauseFly3DPaths: function () {
        var clockViewModel = this.cesiumViewer.clockViewModel;
        if (clockViewModel.shouldAnimate) {
            clockViewModel.shouldAnimate = false;
        } else if (this.cesiumViewer.clockViewModel.canAnimate) {
            clockViewModel.shouldAnimate = true;
        }
    },
    /**
     * 向前飞行漫游路径
     * @method playForwardFly3DPaths
     * @return
     */
    playForwardFly3DPaths: function () {
        var clockViewModel = this.cesiumViewer.clockViewModel;
        var multiplier = clockViewModel.multiplier;
        if (multiplier < 0) {
            clockViewModel.multiplier = -multiplier;
        }
        clockViewModel.shouldAnimate = true;
    },
    /**
     * 向后飞行漫游路径
     * @method playForwardFly3DPaths
     * @return
     */
    playReverseFly3DPaths: function () {
        var clockViewModel = this.cesiumViewer.clockViewModel;
        var multiplier = clockViewModel.multiplier;
        if (multiplier > 0) {
            clockViewModel.multiplier = -multiplier;
        }
        clockViewModel.shouldAnimate = true;
    },
    /**
     * 设定飞行漫游路径
     * @method DrawFly3DPaths
     * @return
     */
    DrawFly3DPaths: function (drawHelper) {
        var T = this;
        this.clearFly3DPaths();
        tracker.trackPolyline(function (positions) {
            T.drawPolyline = new DrawHelper.PolylinePrimitive({
                positions: positions,
                width: 5,
                type: "plot",
                //geodesic: true
            });
            T.cesiumViewer.scene.primitives.add(T.drawPolyline);
            T.drawPolyline.setEditable();
            //构造设定路线的返回信息
            var coordinates = [];
            var position = null;
            var heading = 45; //null;
            var pitch = 45; //null;
            var roll = 45; //null;
            for (var i = 0; i < positions.length; i++) {
                var cartographic = Cesium.Cartographic.fromCartesian(positions[i]); //世界坐标转地理坐标（弧度）
                var point = [cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180]; //地理坐标（弧度）转经纬度坐标
                //console.log(point);
                coordinates.push(point);
            }
            //orientation":{"heading":2.411783930363565,"pitch":-0.21097267398444197,"roll":0.0015622392231300353},"position": {"x":-2206260.239730831,"y":5510911.392077349,"z":2331987.10863007},
            position = drawHelper._cameraPosition;
            heading = drawHelper._cameraHeading;
            pitch = drawHelper._cameraPitch;
            roll = drawHelper._cameraRoll;
            var pathsData = { "orientation": { "heading": heading, "pitch": pitch, "roll": roll }, "position": position, "geometry": { "type": "LineString", "coordinates": coordinates } };

            //var pathsData = { "orientation": { "heading": heading, "pitch": pitch, "roll": roll }, "position": position, "geometry": { "type": "LineString", "coordinates": coordinates } };
            if (FlyCesium) {
                FlyCesium.draw3DObj = T.draw3DObj = pathsData;
                FlyCesium.isDrawFly = true;
            }
            //return T.draw3DObj;
        });
        // drawHelper.startDrawingPolyline({
        //     callback: function(positions) {
        //
        //
        //     }
        // });
    },
    /**
     * 退出飞行漫游路径
     * @method stopFly3DPaths
     * @param
     * @return
     */
    stopFly3DPaths: function () {
        var start = Cesium.JulianDate.fromDate(new Date());
        this.cesiumViewer.clock.startTime = start.clone();
        var stop = Cesium.JulianDate.addSeconds(start, 300000000, new Cesium.JulianDate());
        this.cesiumViewer.clock.stopTime = stop.clone();
        //this.cesiumViewer.entities.remove(this.entityFly);
        this.clearFly3DPaths();
    }
}